package com.focusai.efairy.network.Image;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.webkit.URLUtil;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.focusai.efairy.R;

import java.util.regex.Pattern;

/***
 * @author luo_gw
 */
public class ImageLoaderImpl implements ImageLoader {

    private static final ImageView.ScaleType DEFAULT_SCALETYPE = ImageView.ScaleType.CENTER_CROP;   //默认显示方式

    private static final DiskCacheType DEFAULT_DISKCACHE_TYPE = DiskCacheType.ALL;

    public static final int FADE_DURING = 300;

    @Override
    public void loadImage(Context context, ImageView imageView, int drawableId, int defaultRid, boolean isTran) {
        RequestOptions options = getOptions(ImageView.ScaleType.FIT_CENTER, DiskCacheType.NONE, defaultRid, defaultRid,0,0);
        RequestBuilder<Drawable> requestBuilder = Glide.with(context).load(drawableId);
        if (isTran){
            requestBuilder.transition(DrawableTransitionOptions.withCrossFade(FADE_DURING));
        }
        requestBuilder.apply(options).into(imageView);
    }

    @Override
    public void loadImage(Context context, ImageView imageView, String url, int defaultRid, boolean isTran) {
        RequestOptions options = getOptions(ImageView.ScaleType.CENTER_CROP, DEFAULT_DISKCACHE_TYPE, defaultRid, defaultRid,0,0);
        RequestBuilder<Drawable> requestBuilder = Glide.with(context).load(url);
        if (isTran){
            requestBuilder.transition(DrawableTransitionOptions.withCrossFade(FADE_DURING));
        }
        requestBuilder.apply(options).into(imageView);
    }

    @Override
    public void loadImage(Context context, ImageView imageView, String url) {
        loadImage(context, imageView, url, DEFAULT_SCALETYPE, DEFAULT_DISKCACHE_TYPE);
    }

    @Override
    public void loadImage(Context context, ImageView imageView, String url, ImageView.ScaleType scaleType) {
        loadImage(context, imageView, url, 0, 0, scaleType, DEFAULT_DISKCACHE_TYPE);
    }

    @Override
    public void loadImage(Context context, ImageView imageView, String url, DiskCacheType diskCacheType) {
        loadImage(context, imageView, url, 0, 0, DEFAULT_SCALETYPE, diskCacheType);
    }

    @Override
    public void loadImage(Context context, ImageView imageView, String url, int width, int height) {
        loadImage(context, imageView, url, width, height, 0, 0);
    }


    @Override
    public void loadImage(Context context, ImageView imageView, String url, int width, int height, int placeholderDrawableID, int errorDrawableID) {
        Glide.with(context).load(url).apply( getOptions(DEFAULT_SCALETYPE, DEFAULT_DISKCACHE_TYPE, placeholderDrawableID, errorDrawableID,width,height)).into(imageView);
    }

    @Override
    public void loadImage(Context context, ImageView imageView, String url, int width, int height, ImageView.ScaleType scaleType, DiskCacheType diskCacheType) {
        RequestBuilder<Drawable> requestBuilder = Glide.with(context).load(url).apply(getOptions(scaleType, diskCacheType, 0, 0,width,height));
        requestBuilder.into(imageView);

    }

    @Override
    public void loadImage(Context context, ImageView imageView, String url, ImageView.ScaleType scaleType, DiskCacheType diskCacheType) {
        loadImage(context, imageView, url, scaleType, diskCacheType, 0, 0);
    }

    @Override
    public void loadImage(Context context, ImageView imageView, String url, ImageView.ScaleType scaleType, DiskCacheType diskCacheType, int placeholderDrawableID, int errorDrawableID) {
        Glide.with(context).load(url).apply(getOptions(scaleType, diskCacheType, placeholderDrawableID, errorDrawableID,0,0)).into(imageView);
    }


    private RequestOptions getOptions(ImageView.ScaleType scaleType, DiskCacheType diskCacheType, int placeholderDrawableID, int errorDrawableID,int width, int height) {

        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.default_img_placeholder)
                .error(R.drawable.default_img_error)
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.NONE);
        if (placeholderDrawableID != 0) {
            options.placeholder(placeholderDrawableID);
        }
        if (errorDrawableID != 0) {
            options.error(errorDrawableID);
        }
        if (width != 0 && height != 0) {
            options.override(width, height);
        }
        switch (scaleType) {
            case CENTER:
                options.centerCrop();
                break;
            case CENTER_CROP:
                options.centerCrop();
                break;
            case FIT_XY:
            case FIT_CENTER:
                options.fitCenter();
                break;
            case CENTER_INSIDE:
                options.centerInside();
                break;
            default:
                break;
        }

        switch (diskCacheType) { //由于图片缓存是全局的，所在这里把其设置为缓存源图片
            case ALL:
                options.diskCacheStrategy(DiskCacheStrategy.ALL);
                break;
            case NONE:
                options.diskCacheStrategy(DiskCacheStrategy.NONE);
                break;
            case SOURCE:
                options.diskCacheStrategy(DiskCacheStrategy.RESOURCE);
                break;

            default:
                options.diskCacheStrategy(DiskCacheStrategy.ALL);
                break;
        }
        return options;
    }


    @Override
    public void clearDiskCache(Context context) {
        Glide.get(context).clearDiskCache();
    }

    @Override
    public void clearMemoryCache(Context context) {
        Glide.get(context).clearMemory();
    }

    private static String createNewUrl(String url) {
        if (TextUtils.isEmpty(url) || !URLUtil.isHttpUrl(url)) {
            return url;
        }
        String filename = getFileNameFromUrl(url);
        if (TextUtils.isEmpty(filename))
            return url;
        return url.replace(filename, filename + "_600x600");
    }

    public static String getFileNameFromUrl(String url) {
        if (!TextUtils.isEmpty(url)) {
            int fragment = url.lastIndexOf('#');
            if (fragment > 0) {
                url = url.substring(0, fragment);
            }

            int query = url.lastIndexOf('?');
            if (query > 0) {
                url = url.substring(0, query);
            }

            int filenamePos = url.lastIndexOf('/');
            String filename = 0 <= filenamePos ? url.substring(filenamePos + 1) : url;
            if (!filename.isEmpty() &&
                    Pattern.matches("[a-zA-Z_0-9\\.\\-\\(\\)\\%]+", filename)) {
                int dotPos = filename.lastIndexOf('.');
                if (0 <= dotPos) {
                    return filename.substring(0, dotPos);
                }
            }
        }
        return "";
    }
}
